package entity_model;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import utils.Base;
import utils.titles.Title;

import static entity_model.Relationship.Role.Cardinality;
import static utils.titles.Title.CAPITAL_CASE;


/**
 * Created by nuno-rafael-figueiredo on 07-05-2014.
 */
public class EntityModel extends Base{
    public final ObservableList<Entity> entities = FXCollections.observableArrayList();
    public final ObservableList<Relationship> relationships = FXCollections.observableArrayList();

    public EntityModel(Title title) {
        super(CAPITAL_CASE, title);
    }

    public void createRelationship(Cardinality cardinality, Entity entity, Entity referencedEntity, Title title) {
        add(new Relationship(cardinality, referencedEntity, entity, title));
    }

    public void createRelationship(Cardinality cardinality, Entity entity, Entity referencedEntity) {
        add(new Relationship(cardinality, referencedEntity, entity));
    }

    public Entity getEntity(Title title) {
        for (Entity entity : entities)
            if (entity.getTitle().equals(title))
                return entity;

        Entity entity = new Entity(this, title);
        entities.add(entity);
        return entity;
    }

    public void createRelationship(Entity pivot, Cardinality leftCardinality, Entity leftEntity, Cardinality rightCardinality, Entity rightEntity) {
        add(new Relationship(
                pivot,
                new Relationship.Role(rightEntity, leftCardinality, leftEntity),
                new Relationship.Role(leftEntity, rightCardinality, rightEntity)
        ));
    }

    private void add(Relationship relationship) {
        relationship.getLeftRole().getEntity().add(relationship.getRelated());
        relationship.getRightRole().getEntity().add(relationship.getReversed());

        relationships.add(relationship);
    }
}
